﻿using System;
using System.Net;


using Tulde.Windows.Music.ViewModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Tulde.Windows.Music
{
    /// <summary>
    /// Manages security 
    /// </summary>
    public static class SecurityProvider
    {
        private static ICredentials _Credentials { get;  set; }
        public static NetworkCredential Credentials { get; private set; }
        public static AuthenticationToken Token { get; private set; }
        public static event EventHandler<SecurityProviderEventArgs<ICredentials>> CredentialsChanged;
        public static event EventHandler<SecurityProviderEventArgs<AuthenticationToken>> TokenChanged;
        public static void SetCredentials(ICredentials credentials)
        {
            _Credentials = credentials;
            Credentials = _Credentials.GetCredential(null, "");
            if (CredentialsChanged != null)
            {
                CredentialsChanged(null, new SecurityProviderEventArgs<ICredentials> { Source = Credentials });
            }
        }
        public static void SetAuthenticationTokens( AuthenticationToken token)
        {
            Token = token;
            if (TokenChanged != null)
            {
                TokenChanged(null, new SecurityProviderEventArgs<AuthenticationToken> { Source = token });
            }
        }
        public static ICredentials LoadCredentials()
        {
           BinaryFormatter f = new BinaryFormatter();
           try
           {
               using (FileStream fs = new FileStream("_234124.store", FileMode.Open))
               {
                   return (ICredentials)f.Deserialize(fs);
               }
           }
           catch
           {
               return null;
           }
        }
        public static void SaveCredentials(ICredentials c)
        {
            BinaryFormatter f = new BinaryFormatter();
           using( FileStream fs = new FileStream("_234124.store",FileMode.Create) )
           {
               f.Serialize(fs, c);
           }
        }
    }
    public class SecurityProviderEventArgs<T> : EventArgs
    {
        public T Source { get; set; }
    }
   
}
